<template>
    <view>
        <view>
          <view v-show="isTip" @touchmove.stop.prevent="stopSlide">
            <view class="mask" @click="isTip=false"></view>
            <view class="tip">点击右上角分享符，分享有礼 ↑</view>
          </view>
        </view>
        <docview :srcData="docUrl"/>
        <view class="footer">
            <view class="footer_btn">
                <button class="weui-btn1" open-type="share" v-if="isLogin" @click="showShare">收&nbsp;&nbsp;&nbsp;&nbsp;藏</button>
                <button class="weui-btn2" @tap="buyNow" v-if="(goods.pay==false)&&goods.amount>0">购买金额&nbsp;￥{{goods.amount}}</button>
                <button class="weui-btn2" v-if="goods.isFree==0&&goods.pay==true">已&nbsp;购&nbsp;买</button>
                <button class="weui-btn2" v-if="goods.isFree==1" @click="downLoad">下&nbsp;&nbsp;&nbsp;&nbsp;载</button>
            </view>
        </view>
    </view>
</template>
<script>
var config = require('../../../config.js');
var http = require('../../../utils/httpHelper.js');
import docview from '@/components/docview/docview';
import wx from 'weixin-js-sdk';
export default {
    components: {
        docview
    },
    data() {
        return {
            //是否自动切换
            current: 0,
            //滑动时间
            clas: ['action'],
            goodsData: [],
            goodsDataAll: [],
            curD: 0,
            userInfo: {},
            isLogin: false,
            indicatorDots: true,
            //是否显示面板指示点
            autoplay: false,
            //是否自动切换
            interval: 5000,
            //自动切换时间
            duration: 1000,
            //滑动时间
            buyCount: 1,            
            goods: {},
            docUrl: '',
            buyCount: '1',
            productPics: [],
            productVids: [],
            showDoc: false,
            isTip: false
        };
    },
    onLoad: function (options) {
        var that = this;      
        let userInfo = uni.getStorageSync('user');
        if (userInfo != null && userInfo != undefined && userInfo != {} && userInfo != '') {
            that.setData({
                isLogin: true,
                userInfo: userInfo
            });
        } else {
            uni.setStorageSync('inviteId', options.inviteId);
        }
        var id = options.id;
        that.getGoodsInfo(id);        
        setTimeout(()=>{
            this.share();
        },6000)        
    },
    onShow: function () {
        let userInfo = uni.getStorageSync('user');
        if (userInfo != null && userInfo != undefined && userInfo != {} && userInfo != '') {
            this.setData({
                isLogin: true,
                userInfo: userInfo
            });
        }
    },    
    methods: {
        onNavigationBarButtonTap: function (e) {
          console.log('onNavigationBarButtonTap',e);
        },
        getGoodsInfo: function (id) {
            var curUserId = 0;
            if (this.userInfo.userId) {
              curUserId = this.userInfo.userId;
            }
            var that = this;
            var data = {
                id: id,
                userId: curUserId
            };
            http.httpGet(config.clubApi.getMaterialInfo, data, function (res) {
                if (res.code == '200') {
                    var goods = res.data;
                    if (goods.url==null||goods.url=='null'||goods.url=='') {
                      uni.showToast({
                        title: '没有可浏览资料',
                        icon: 'none',
                        duration: 3000
                      });
                      setTimeout(function(){
                        that.$router.back();
                      },1000);
                      return;
                    }
                    that.showDoc = false;
                    if (goods.pay==true) {
                      that.showDoc = true;                      
                    }
                    let url = goods.url;
                    that.setData({
                        goods: goods,
                        docUrl: url
                    });
                    var data = {
                        appId: config.APPID,
                        materialId: goods.id,
                        userId: curUserId
                    };
                    http.httpPut(config.clubApi.createView, data, function (res) {                        
                    });
                }
            });
        },

        buyNow: function (e) {
            if (this.isLogin && uni.getStorageSync('user')) {
                this.settlement();
            } else {
                uni.switchTab({
                    url: '/pages/user/index'
                });
            }
        },
        createOrder: function (buyGoods, callback) {
            http.httpPut(config.clubApi.createOrderzl, buyGoods, function (res) {
                if (res.code == '200') {
                    //订单创建成功
                    if (typeof callback == 'function') {
                        callback(res);
                    }
                } else {
                    //订单创建失败
                    if (typeof callback == 'function') {
                        callback('');
                    }
                }
            });
        },        
        settlement: function () {
            var that = this;            
            //继续生成订单
            var userId = that.userInfo.userId;
            var data = {
                appid: config.APPID,
                materialId: that.goods.id,
                userId: userId,
                amount: that.goods.amount,
                realAmount: that.goods.amount,
            };
            this.createOrder(data, function (res) {
                if (res.code == '200') {
                    try {
                        let params = res.data;
                        WeixinJSBridge.invoke('getBrandWCPayRequest', params, function (res) {
                            if (res.err_msg == 'get_brand_wcpay_request:ok') {
                                uni.showToast({
                                    title: '支付成功',
                                    icon: 'none',
                                    duration: 3000
                                });
                                that.showDoc = true;
                                that.goods.productPics = that.productVids;
                            } else {
                                uni.showToast({
                                    title: '支付失败',
                                    icon: 'none',
                                    duration: 3000
                                });
                                that.showDoc = false;
                                that.goods.productPics = that.productPics;
                            }
                            uni.setStorageSync('shoppingcar', []);
                        });
                    } catch (f) {
                        console.log('CatchClause', f);
                        console.log('CatchClause', f);
                        if (res.msg) {
                            uni.showToast({
                                title: res.msg,
                                icon: 'none',
                                duration: 2000
                            });
                        }
                        uni.setStorageSync('shoppingcar', []);
                        that.showDoc = false;
                        that.goods.productPics = that.productPics;
                    }
                    uni.setStorageSync('shoppingcar', []);                    
                }
            });
        },
        getSignUrl(){
            var signLink = ''
            var ua = navigator.userAgent.toLowerCase();
            if (/iphone|ipad|ipod/.test(ua)) {                
                signLink = 'http://jkhmzw.shudingkj.com/pages/material/detail/index?id='+this.goods.id+'&inviteId='+this.userInfo.userId;
            } else {
                signLink = location.href
            }
            return signLink;
        },
        stopSlide() {
          return;
        },
        showShare() {
          //this.isTip = true;
          if (this.isLogin && uni.getStorageSync('user')) {
            var goods = this.goods;
            if (goods.url=='null'||goods.url=='') {
              uni.showToast({
                title: '没有可收藏资料',
                icon: 'none',
                duration: 3000
              }); 
              return;
            }
            var idParam = goods.id;
            var data = {
                appId: config.APPID,
                materialId: idParam,                
                userId: this.userInfo.userId
            };
            http.httpPut(config.clubApi.createCollect, data, function (res) {
                uni.showToast({
                    title: res.msg,
                    icon: 'none',
                    duration: 3000
                });
            });
          }
        },
        downLoad() {
          if (this.isLogin && uni.getStorageSync('user')) {
            var goods = this.goods;
            if (goods.url=='null'||goods.url=='') {
              uni.showToast({
                title: '没有可下载资料',
                icon: 'none',
                duration: 3000
              }); 
              return;
            }
            var data = {
                appId: config.APPID,
                materialId: goods.id,                
                userId: this.userInfo.userId
            };
            http.httpPut(config.clubApi.createDown, data, function (res) {
                if (res.code == '200') {
                    location.href = goods.url;
                    uni.showToast({
                        title: res.msg,
                        icon: 'none',
                        duration: 3000
                    });
                } else {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none',
                        duration: 3000
                    });
                }
            });
          } else {
            uni.switchTab({
              url: '/pages/user/index'
            });
          }
        },
        share() {          
          var goods = this.goods;
          var curUrl = this.getSignUrl();
          const jsApiList=[
            'checkJsApi', //检测接口权限	
            'updateTimelineShareData',
            'updateAppMessageShareData',
            'openLocation'
          ];
          //这是后端写的接口，需要用后端返回内容配置微信分享的参数
          uni.request({
            method: 'GET',
            url: config.BASE_URL + '/auth/getWXInterface',
            data: {
              url:curUrl,
              appid:config.APPID
            },
            header: {
                'U-TOKEN': uni.getStorageSync('user') ? uni.getStorageSync('user').token : '/pages/detail/index',
                "Content-Type": "application/json"
            },
            success: (res) => {
                if (res.statusCode == 401) {
                    uni.setStorageSync('user', null);
                }
                if (typeof cb == 'function') {
                    cb(res.data, '');
                }
                uni.hideNavigationBarLoading();
                if (res.statusCode == '200') {                  
                  wx.config({
                    debug:false,
                    appId:config.APPID,
                    timestamp:res.data.data.timestamp,
                    nonceStr:res.data.data.nonceStr,
                    signature:res.data.data.signature,					
                    jsApiList
                  });
                  wx.ready(() => {
                      var tempParam = {
                        title: goods.materialName,
                        desc: goods.age+goods.gradeName+goods.semesterName,
                        link: curUrl,
                        imgUrl: 'http://jkhmzw.shudingkj.com/static/images/logo.jpg',
                        success: (res) => {
                          console.log(res) 
                        },
                        cancel: function (res) {
                          console.log('分享失败', res)
                        },
                      }
                      if(wx.updateAppMessageShareData) {
                        wx.updateAppMessageShareData(tempParam);                    
                      } else {
                        wx.onMenuShareAppMessage(tempParam);
                      }
                  });
                  wx.ready(() => {
                      var tempParam = {
                        title: goods.materialName,
                        desc: goods.age+goods.gradeName+goods.semesterName,
                        link: curUrl,
                        imgUrl: 'http://jkhmzw.shudingkj.com/static/images/logo.jpg',
                        success: (res) => {
                          console.log(res) 
                        },
                        cancel: function (res) {
                          console.log('分享失败', res)
                        },
                      }
                      if(wx.updateTimelineShareData) {
                        wx.updateTimelineShareData(tempParam);
                      } else {
                        wx.onMenuShareAppMessage(tempParam);
                      }
                  });
                  wx.error(function(res){
                    console.log(res.errMsg);
                  })
                  // 判断客户端是否支持指定js的接口
                  wx.checkJsApi({
                    jsApiList,
                    success: function (res) {	       		
                      console.log('判断客户端支持js接口', res)
                    },
                  })
                }
            },
            fail: (err) => {
                if (typeof cb == 'function') {
                    cb(null, err.errMsg);
                }
                uni.hideNavigationBarLoading();
            }
          })
        }
    }
};
</script>
<style lang="scss">
@import './index.scss';
</style>
